package com.pcj.blog.handler;/**
 * @param
 * @author pcj
 * @date 2021/12/23 11:40
 * @return
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @className ControllerException
 * @author pengcj
 * @date 2021/12/23 11:40
 */
@ControllerAdvice
public class ControllerException {

    private Logger logger= LoggerFactory.getLogger(this.getClass());
    @ExceptionHandler(Exception.class)//标识这个方法可以做异常处理  表示拦截的信息是Exception级别的都可以
    public ModelAndView exceptionhandler(HttpServletRequest request,Exception e) throws Exception {
    logger.error("Request Url : {},Exception : {}",request.getRequestURL(),e); //记录异常信息
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){ // findAnnotation 从类或方法中查找某个annotation。
            throw e;
        }
        ModelAndView mv=new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("Exception",e);
        mv.setViewName("error/error"); //返回页面
        return  mv;
    }
}
